package com.tduck.cloud.api.web.controller.form;


import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tduck.cloud.common.util.RedisUtils;
import com.tduck.cloud.common.util.SecurityUtils;
import com.tduck.cloud.common.util.ShortIdUtils;
import com.tduck.cloud.form.constant.FormRedisConstants;
import com.tduck.cloud.form.entity.FormDataSourceEntity;
import com.tduck.cloud.form.service.FormDataSourceService;
import com.tduck.cloud.form.util.FormSyncUtils;
import org.springframework.web.bind.annotation.*;
import com.tduck.cloud.common.util.Result;

import javax.annotation.Resource;
import java.util.List;

/**
 * 表单数据源(FormDataSource)表控制层
 *
 * @author makejava
 * @since 2024-04-06 12:36:14
 */
@RestController
@RequestMapping("/form/dataSource")
public class FormDataSourceController {
    /**
     * 服务对象
     */
    @Resource
    private FormDataSourceService formDataSourceService;
    @Resource
    private FormSyncUtils formSyncUtils;
    @Resource
    private RedisUtils redisUtils;

    /**
     * 分页查询所有数据
     *
     * @param page           分页对象
     * @param formDataSource 查询实体
     * @return 所有数据
     */
    @GetMapping("/page")
    public Result page(Page<FormDataSourceEntity> page, FormDataSourceEntity formDataSource) {
        formDataSource.setUserId(SecurityUtils.getUserId());
        Page<FormDataSourceEntity> sourceEntityPage = formDataSourceService.page(page, new QueryWrapper<>(formDataSource));
        sourceEntityPage.getRecords().forEach(item -> {
            Long count = redisUtils.get(StrUtil.format(FormRedisConstants.FORM_DATA_COUNT, item.getFormKey()), Long.class);
            item.setDataCount(count);
        });
        return Result.success(sourceEntityPage);
    }


    /**
     * 获取表单列表
     *
     * @return
     */
    @GetMapping("/list")
    public Result<List<FormDataSourceEntity>> getFormList() {
        return Result.success(formDataSourceService.list(Wrappers.<FormDataSourceEntity>lambdaQuery().eq(FormDataSourceEntity::getUserId, SecurityUtils.getUserId())));
    }


    /**
     * 获取表单列表
     *
     * @return
     */
    @GetMapping("/fields")
    public Result getFormFields(String formKey) {
        FormDataSourceEntity one = formDataSourceService.getOne(Wrappers.<FormDataSourceEntity>lambdaQuery().eq(FormDataSourceEntity::getUserId, SecurityUtils.getUserId()).eq(FormDataSourceEntity::getFormKey, formKey));
        if (null != one) {
            return Result.success(one.getFields());
        }
        return Result.success();
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public Result getById(@PathVariable Long id) {
        return Result.success(formDataSourceService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param formDataSource 实体对象
     * @return 新增结果
     */
    @PostMapping("/add")
    public Result add(@RequestBody FormDataSourceEntity formDataSource) {
        formDataSource.setFormKey(ShortIdUtils.genId());
        formDataSource.setUserId(SecurityUtils.getUserId());
        boolean save = formDataSourceService.save(formDataSource);
        return Result.success();
    }

    /**
     * 修改数据
     *
     * @param formDataSource 实体对象
     * @return 修改结果
     */
    @PostMapping("update")
    public Result update(@RequestBody FormDataSourceEntity formDataSource) {
        formDataSource.setUserId(SecurityUtils.getUserId());
        return Result.success(formDataSourceService.updateById(formDataSource));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @PostMapping("delete")
    public Result delete(@RequestParam("idList") List<Long> idList) {
        return Result.success(formDataSourceService.removeByIds(idList));
    }

    @PostMapping("/syncFields")
    public Result syncFields(@RequestParam("id") Long formId, String url) {
        formSyncUtils.syncField(url, formId);
        return Result.success();
    }

    @PostMapping("/syncData")
    public Result syncData(@RequestParam("id") Long formId, String url) {
        ThreadUtil.execAsync(() -> {
            formSyncUtils.syncData(url, formId);
        });
        return Result.success();
    }
}

